import java.util.LinkedList;


public class Expression extends LinkedList<NumSign> {
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        for (NumSign numSign : this) {
            str.append(numSign.getStrNum()).append(numSign.getSign());
        }
        return str.toString();
    }

    public double calculate() {
        try {
            calMuAndDiv();
            calAddAndSub();
        } catch (ArithmeticException e) {
            System.err.println("Error in calculation: " + e.getMessage());
            return Double.NaN;
        }
        return this.get(0).getNum();
    }

    private void calMuAndDiv() {
        for (int i = 0; i < this.size(); i++) {
            System.out.println(this.toString());
            if (this.size() == 1) return;
            if (this.get(i).getSign() == '*') {
                double temp = this.get(i).getNum() * this.get(i + 1).getNum();
                this.get(i + 1).setNum(temp);
                this.remove(i);
                i--;
            } else if (this.get(i).getSign() == '/') {
                if (this.get(i + 1).getNum() == 0) {
                    throw new ArithmeticException("Division by zero");
                }
                double temp = this.get(i).getNum() / this.get(i + 1).getNum();
                this.get(i + 1).setNum(temp);
                this.remove(i);
                i--;
            }
        }
    }

    private void calAddAndSub() {
        for (int i = 0; i < this.size(); i++) {
            System.out.println(this.toString());
            if (this.size() == 1) return;
            if (this.get(i).getSign() == '+') {
                double temp = this.get(i).getNum() + this.get(i + 1).getNum();
                this.get(i + 1).setNum(temp);
                this.remove(i);
                i--;
            } else if (this.get(i).getSign() == '-') {
                double temp = this.get(i).getNum() - this.get(i + 1).getNum();
                this.get(i + 1).setNum(temp);
                this.remove(i);
                i--;
            }
        }
    }
}